package com.yoga.manager.uitl;



import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;

/**
 * md5密码加密
 * */
public class MD5Util {

    private static final String KEY="rabbit@$$@";

    public static String encryption(String str) throws Exception {

        if (StringUtils.isEmpty(str)){
            throw new AppException(AppErrorCodeEnum.PARAMETER_NULL);
        }

            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
        return buf.toString().toUpperCase();
    }

    public static String passWord(String passWd) throws AppException{
        if (StringUtils.isEmpty(passWd)){
            throw new AppException(AppErrorCodeEnum.PARAMETER_NULL);
        }
        StringBuffer buffer=new StringBuffer();
        buffer.append(KEY).append(passWd);
        try {
            return MD5Util.encryption(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(AppErrorCodeEnum.SYSTEM_ERROR);
        }
    }

  //C12D89A96EDA73110E684B146ECBBFE8
    public static void main(String[] args) {
        String str=MD5Util.passWord("czt123");
        System.out.println(str);
        System.out.println(str+" length="+str.length());
    }

}
